<?php


namespace app\api\wxpay;

class WechatPaySdk
{
	public $merchant_id = "";
	public $mch_serial_no = "";
	public $merchantPrivateKeyFilePath = "";
	public $platformCertificateFilePath = "";
	public $apiv3key = "";
	public $appid = "";
	public $platformCertificateId = "";
	public function __construct($config)
	{
		$this->appid = \strval($config["appid"]);
		$this->merchant_id = \strval($config["merchant_id"]);
		$this->mch_serial_no = \strval($config["mch_serial_no"]);
		$this->apiv3key = \strval($config["apiv3key"]);
		$this->platformCertificateId = \strval($config["platformCertificateId"] ?? "");
		$this->merchantPrivateKeyFilePath = get_cert_path("system", "wechat.merchantPrivateKey.pem", $config["merchantPrivateKey"]);
		$this->platformCertificateFilePath = empty($config["platformCertificate"]) ? "" : get_cert_path("system", "wechat.platformCertificate.pem", $config["platformCertificate"]);
	}
	public function instance()
	{
		$merchantId = $this->merchant_id;
		$merchantPrivateKeyFilePath = "file://" . $this->merchantPrivateKeyFilePath;
		$merchantPrivateKeyInstance = \WeChatPay\Crypto\Rsa::from($merchantPrivateKeyFilePath, \WeChatPay\Crypto\Rsa::KEY_TYPE_PRIVATE);
		$merchantCertificateSerial = $this->mch_serial_no;
		$platformCertificateFilePath = "file://" . $this->platformCertificateFilePath;
		$platformPublicKeyInstance = \WeChatPay\Crypto\Rsa::from($platformCertificateFilePath, \WeChatPay\Crypto\Rsa::KEY_TYPE_PUBLIC);
		$platformCertificateSerial = $this->platformCertificateId ?: \WeChatPay\Util\PemUtil::parseCertificateSerialNo($platformCertificateFilePath);
		$instance = \WeChatPay\Builder::factory(["mchid" => $merchantId, "serial" => $merchantCertificateSerial, "privateKey" => $merchantPrivateKeyInstance, "certs" => [$platformCertificateSerial => $platformPublicKeyInstance]]);
		return $instance;
	}
}